package com.link.base.base.passwdhistory.service;

import com.link.base.base.passwdhistory.dao.mybatis.mapper.PasswdHistoryMapper;
import com.link.base.base.passwdhistory.model.PasswdHistory;
import com.link.base.base.user.dao.mybatis.mapper.UserMapper;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.util.PasswordUtil;
import com.link.base.core.basic.util.YmlConstants;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author unknown
 * @date unknown
 * @comments 密码历史服务
 */
@Service
public class PasswdHistoryServiceImpl extends BasicServiceImpl<PasswdHistory> implements PasswdHistoryService {

    @Resource
    private PasswdHistoryMapper passwdHistoryMapper;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private UserMapper userMapper;

    @Override
    public BasicMapper<PasswdHistory> getBasicMapper() {
        return passwdHistoryMapper;
    }

    /**
     * @author huanglongjian
     * @param newPasswd 新密码（加密过的）
     * @param monthNum  有效期 （月份为单位）
     * @return
     * @throws Exception
     * @校验历史密码, 如果返回值false，表示历史密码已经存在，禁止使用
     */
    @Override
    public boolean checkHistory(String newPasswd, int monthNum, String userName) throws Exception {
        String newEncordePassword = PasswordUtil.generatePwd(newPasswd);
        Date date = new Date();
        Calendar cl = Calendar.getInstance();
        cl.setTime(date);
        cl.add(Calendar.MONTH, 0 - monthNum);
        date = cl.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String compDate = sdf.format(date);

        //因为当前还没登录，所以通过jdbcTemplate查询库
        String sql = null;
        String database = YmlConstants.getApplicationDatabase();
        String baseType = "mysql";
        if (baseType.equals(database)) {
            sql = "select T1.PASSWD from  LNK_PW_HISTORY T1 where T1.USER_NAME  = '" + userName
                    + "' and T1.MODIFY_DT > str_to_date('" + compDate + "', '%Y-%m-%d');";
        } else {
            sql = "select T1.PASSWD from  LNK_PW_HISTORY T1 where T1.USER_NAME  = '" + userName
                    + "' and T1.MODIFY_DT > to_date('" + compDate + "', 'yyyy-MM-dd')";
        }
        List rows = jdbcTemplate.queryForList(sql);
        Iterator it = rows.iterator();
        while (it.hasNext()) {
            Map psswdStrMap = (Map) it.next();
            if (newEncordePassword.equals(psswdStrMap.get("PASSWD"))) {
                return false;
            }
        }
        return true;
    }

}
